package com.chat.room.service;

import com.chat.room.common.CommonConstant;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;

@Data
@Slf4j
@AllArgsConstructor
public class SearchListener implements Runnable {

    private DatagramSocket datagramSocket;

    public boolean flag = true;

    @Override
    public void run() {
        log.info("服务监听器开始运行");
        while (flag) {
            try {
                listenerAndResponse();
            } catch (IOException e) {
                log.error("监听异常退出:{}", e);
            }
        }
        log.info("监听器退出");
    }

    /**
     * 关闭服务监听程序
     */
    public void close() {
        flag = false;
        if (datagramSocket != null) {
            datagramSocket.close();
        }
    }

    public void listenerAndResponse() throws IOException {
        byte[] bytes = new byte[512];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
        datagramSocket.receive(datagramPacket);
        String receiveInfo = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
        InetAddress address = datagramPacket.getAddress();
        log.info("收到客户端{}发送消息：{}", address, receiveInfo);
        if (!StringUtils.isEmpty(receiveInfo) && receiveInfo.startsWith(CommonConstant.COMMONS_SEARCH_INFO)) {
            int port = Integer.parseInt(receiveInfo.replace(CommonConstant.COMMONS_SEARCH_INFO, ""));
            log.info("回送消息端口：{}", port);
            ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[512]);
            byteBuffer.putInt(CommonConstant.SERVICE_TRANS_PORT);
            datagramPacket = new DatagramPacket(byteBuffer.array(), byteBuffer.limit());
            datagramPacket.setAddress(address);
            datagramPacket.setPort(port);
            datagramSocket.send(datagramPacket);
        }
    }


}